#ifndef UNIX
# define GLEW_STATIC 1
#endif

#include <GL/glew.h>

#include "../host.h"

GLenum texEnvParams[] =
{
    GL_COMBINE_RGB,
    GL_COMBINE_ALPHA,
    GL_RGB_SCALE,
    GL_ALPHA_SCALE,
    GL_SRC0_RGB,
    GL_SRC1_RGB,
    GL_SRC2_RGB,
    GL_SRC0_ALPHA,
    GL_SRC1_ALPHA,
    GL_SRC2_ALPHA,
    GL_OPERAND0_RGB,
    GL_OPERAND1_RGB,
    GL_OPERAND2_RGB,
    GL_OPERAND0_ALPHA,
    GL_OPERAND1_ALPHA,
    GL_OPERAND2_ALPHA,
    GL_TEXTURE_ENV_MODE
};

GLenum texEnvValues[] =
{
    GL_MODULATE,
    GL_DECAL,
    GL_BLEND,
    GL_REPLACE,
    GL_ADD,
    GL_INTERPOLATE,
    GL_SUBTRACT,
    GL_TEXTURE,
    GL_CONSTANT,
    GL_PREVIOUS,
    GL_SRC_COLOR,
    GL_SRC_ALPHA,
    GL_COMBINE
};

GLenum texFmts[] =
{
    GL_RGB,
    GL_RGBA,
    GL_RGBA,
    GL_RGBA
};

GLenum texTypes[] =
{
    GL_UNSIGNED_SHORT_5_6_5_REV,
    GL_UNSIGNED_SHORT_1_5_5_5_REV,
    GL_UNSIGNED_SHORT_4_4_4_4_REV,
    GL_UNSIGNED_BYTE
};

u32 host_genTex()
{
    u32 id;
    glGenTextures(1, &id);
    return id;
}

void host_delTex(u32 id)
{
    glDeleteTextures(1, &id);
}

void host_setTex(u32 texId)
{
    glBindTexture(GL_TEXTURE_2D, texId);
}

void host_setTexImage(u32 level, u32 width, u32 height, RETexFormat format, void *texArray)
{
    glTexImage2D(GL_TEXTURE_2D, level, texFmts[format], width, height, 0, texFmts[format], texTypes[format], texArray);
}

void host_setTexParam(u8 sClamp, u8 tClamp, u8 magFilt, u8 minFilt)
{
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, sClamp ? GL_CLAMP_TO_EDGE : GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, tClamp ? GL_CLAMP_TO_EDGE : GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilt ? GL_LINEAR : GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilt ? GL_LINEAR : GL_NEAREST);
}

void host_setTexRgbScale(float scale)
{
    glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE, scale);
}

void host_setTexEnvColor(float color[4])
{
    glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, color);
}

void host_setTexEnvParam(RETexEnvParam param, RETexEnvValue value)
{
    GLenum glParam = texEnvParams[param];
    GLenum glValue = texEnvValues[value];
    glTexEnvi(GL_TEXTURE_ENV, glParam, glValue);
}

void host_setPixelStore(u32 rowLength, u32 alignment)
{
    glPixelStorei(GL_UNPACK_ROW_LENGTH, rowLength);
    glPixelStorei(GL_UNPACK_ALIGNMENT, alignment);
    glPixelStorei(GL_PACK_ROW_LENGTH, rowLength);
    glPixelStorei(GL_PACK_ALIGNMENT, alignment);
}

